﻿(function($){
/*
 * @author denisdeng dexibe@gmail.com
 * blog www.denisdeng.com
 * $Version: 2009.8.11 1.0
 * param reg[String] the format of image;
 * param defImg[String] the default image;
 * param btnText[String] the text of button;
 * param error[String] the error;
 * param imgText[String] the text when image do not show normaly;
 */

$.fn.liveFakeFile = function(o){
	var settings = {
			reg:"png|jpe?g|gif|bmp",
			defImg:'img/defImage.gif',
			btnText:'浏览图片',
			blankImg: "img/blank.gif",
			error: '对不起,照片格式不正确,请重新选择',
			imgText:'你已经选择文件'
	};
	var ie7 = $.browser.msie&&($.browser.version == "7.0");
	var ie8 = $.browser.msie&&($.browser.version == "8.0");
	var moz = $.browser.mozilla;
	return this.each(function(i,v){
		if(o) settings = $.extend(settings, o);
		var wrap = $('<div class="fakefile"></div>');
		var mes = $('<p class="mes"></p>');
		var button = $('<button type="button"></button>');
		var parent = $(this).parent('.fileinputs');
		var imgWrap = $('<div class="imgWrap"></div>');
		var defImg = $('<img src="'+settings.defImg+'" />');
		imgWrap.append(defImg);
		button.append(settings.btnText);
		wrap.append(button);
		wrap.append(mes);
		imgWrap.insertBefore($(this));		
		$(this).attr("id",'file_'+i).appendTo(wrap);
		parent.append(wrap);
		$(this).bind('change',function(){
			var val = $(this).val();
			var imgName = val.slice(val.lastIndexOf("\\")+1);
			if(val.match(new RegExp(".(" + settings.reg + ")$", "i"))){
				mes.empty();
				//针对不能正常显示图片的浏览器
				var img = $('<span></span>') .append(settings. imgText).append(imgName);
				//针对IE7或IE8浏览器
				if(ie7 || ie8){
					var img = $('<img src="'+ settings.blankImg+'" alt="" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=\'scale\',src=\''+val+'\');" />');
				}
				//针对火狐浏览器
				if(moz){
					var obj = document.getElementById('file_'+i);
					var img = $('<img src="'+obj.files[0].getAsDataURL()+'" alt="" width="75" />');
				}
				imgWrap.empty().append(img);
			}else{
				imgWrap.empty().append(defImg);
				mes.html(settings.error);
			}
		});
	})
}
})(jQuery)